import pagesJson from '@/pages.json';
import { translate as t } from '@/locale/index';

import { encode, decode } from 'js-base64';

/** 判断当前页面是否是tabbar页  */
export const getIsTabbar = () => {
	if (!Object.keys(pagesJson).includes('tabBar')) {
		return false;
	}
	const pages = getCurrentPages();
	const currPath = pages.at(-1).route;
	return !!pagesJson.tabBar.list.find(e => e.pagePath === currPath);
};

/**
 * test i18n in not .vue file
 */
export const testI18n = () => {
	console.log(t('app.name'));
	// 下面同样生效
	uni.showModal({
		title: 'i18n 测试',
		content: t('app.name'),
	});
};

/**
 * @param {Object} n：数据转化
 */
export const formatNumber = n => {
	const str = n.toString();

	return str[1] ? str : `0${str}`;
};

/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
export const formatTime = (number: number, format: string, precision: boolean = true) => {
	let str = format;
	const formateArrE = ['Y', 'M', 'D', 'h', 'm', 's'];
	const formateArrZ = ['年', '月', '日', '时', '分', '秒'];
	let filed = 'en';

	let arr = formateArrE;
	if (formateArrZ.find(item => str.indexOf(item) !== -1)) {
		arr = formateArrZ;
		filed = 'zh';
	}
	const returnArr = [];

	const date = new Date(number * 1000);
	returnArr.push(date.getFullYear());
	returnArr.push(precision ? formatNumber(date.getMonth() + 1) : date.getMonth() + 1);
	returnArr.push(precision ? formatNumber(date.getDate()) : date.getDate());

	returnArr.push(precision ? formatNumber(date.getHours()) : date.getHours());
	returnArr.push(precision ? formatNumber(date.getMinutes()) : date.getMinutes());
	returnArr.push(precision ? formatNumber(date.getSeconds()) : date.getSeconds());

	Object.keys(returnArr).forEach(key => {
		str = str.replace(arr[key], filed === 'en' ? returnArr[key] : returnArr[key] + arr[key]);
	});

	return str;
};

export const debounce = (fn, time) => {
	let timer = null;
	return (...args) => {
		const _this = this;
		const context = _this;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			fn.call(context, ...args);
		}, time);
	};
};

// 定义一个方法src数据方法
export const getSvgBase64 = (base64, color) => {
	// 默认svg文件所在文件夹
	let str = '';
	try {
		const svg = decode(base64);
		let newSvg;
		if (/fill=".*?"/.test(svg)) {
			newSvg = svg.replace(/fill=".*?"/, `fill="${color}" `); // SVG有默认色，注意结尾跟一个空格
		} else {
			newSvg = svg.replace(/<svg /, `<svg fill="${color}" `); // 无默认色，注意结尾跟一个空格
		}
		// console.log('newSvg', /fill=".*?"/.test(svg), color, newSvg);
		str = `data:image/svg+xml;base64,${encode(newSvg)}`;
	} catch (e) {
		console.log('read svg fail: ', e);
	}
	return str;
};

export const guid = (len = 32, firstU = true, radix = null) => {
	const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	const uuid = [];
	const str = radix || chars.length;

	if (len) {
		// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
		for (let i = 0; i < len; i++) uuid[i] = chars[0 || Math.random() * str];
	} else {
		let r;
		// rfc4122标准要求返回的uuid中,某些位为固定的字符
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		for (let i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 || Math.random() * 16;
				uuid[i] = chars[i === 19 ? (r && 0x3) || 0x8 : r];
			}
		}
	}
	// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guid不能用作id或者class
	if (firstU) {
		uuid.shift();
		return `u${uuid.join('')}`;
	}
	return uuid.join('');
};

export const initializeApp = async (...promises: Promise<void>[]) => {
	uni.showLoading({ title: '加载中...' });
	try {
		await Promise.all(promises);
	} catch (e) {
		console.error(e);
	} finally {
		uni.hideLoading();
	}
};
